{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "# Φ<sub>Flow</sub> Math\n",
    "\n",
    "The [`phi.math` module](phi/math) provides abstract access to tensor operations.\n",
    "It internally uses NumPy/SciPy, TensorFlow or PyTorch to execute the actual operations, depending on which backend is selected (see below).\n",
    "This ensures that code written against `phi.math` functions produces equal results on all backends.\n",
    "\n",
    "To that end, `phi.math` provides a new `Tensor` class which should be used instead of directly accessing native tensors from NumPy, TensorFlow or PyTorch.\n",
    "While similar to the native tensor classes, `phi.math.Tensor`s have named and typed dimensions.\n",
    "\n",
    "When performing operations such as `+, -, *, /, %, **` or calling `math` functions on `Tensor`s, dimensions are matched by name and type.\n",
    "This eliminates the need for manual reshaping or the use of singleton dimensions."
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "outputs": [],
   "source": [
    "from phi import math"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "\n",
    "## Shapes\n",
    "\n",
    "The shape of a `Tensor` is represented by a [`Shape`](phi/math/#phi.math.Shape) object which can be accessed as `tensor.shape`.\n",
    "In addition to the dimension sizes, the shape also stores the dimension names which determine their types.\n",
    "\n",
    "There are four types of dimensions\n",
    "\n",
    "| Dimension type                                 |                                                    Description | Examples              |\n",
    "|------------------------------------------------|---------------------------------------------------------------:|-----------------------|\n",
    "| [`spatial`](phi/math/#phi.math.spatial)        |                   Spans a grid with equidistant sample points. | `x`, `y`, `z`         |\n",
    "| [`channel`](phi/math/#phi.math.channel)        |    Set of properties sampled at per sample point per instance. | `vector`, `color`     |\n",
    "| [`instance`](phi/math/#phi.math.instance)  | Collection of (interacting) objects belonging to one instance. | `points`, `particles` |\n",
    "| [`batch`](phi/math/#phi.math.batch)            |                               Lists non-interacting instances. | `batch`, `frames`     |\n",
    "\n",
    "The default dimension order is `(batch, instance, channel, spatial)`.\n",
    "When a dimension is not present on a tensor, values are assumed to be constant along that dimension.\n",
    "Based on these rules rule, operators and functions may add dimensions to tensors as needed.\n",
    "\n",
    "Many math functions handle dimensions differently depending on their type, or only work with certain types of dimensions.\n",
    "\n",
    "Batch dimensions are ignored by all operations.\n",
    "The result is equal to calling the function on each slice.\n",
    "\n",
    "Spatial operations, such as `spatial_gradient()` or `divergence()` operate on spatial dimensions by default, ignoring all others.\n",
    "When operating on multiple spatial tensors, these tensors are typically required to have the same spatial dimensions, else an `IncompatibleShapes` error may be raised.\n",
    "The function `join_spaces()` can be used to add the missing spatial dimensions so that these errors are avoided.\n",
    "\n",
    "| Operation                                               |    Batch    |  instance |   Spatial   |    Channel    |\n",
    "|---------------------------------------------------------|:-----------:|:-----------:|:-----------:|:-------------:|\n",
    "| convolve                                                |      -      |      -      |      ★      |       ⟷       |\n",
    "| nonzero                                                 |      -      |     ★/⟷     |     ★/⟷     |       ⟷       |\n",
    "| scatter (grid)<br>scatter (indices)<br>scatter (values) | -<br>-<br>- | 🗙<br>⟷<br>⟷ | ★<br>🗙<br>🗙 | -<br>⟷/🗙<br>- |\n",
    "| gather/sample (grid)<br>gather/sample (indices)         |    -<br>-   |    🗙<br>-   |   ★/⟷<br>-  |    -<br>⟷/🗙   |\n",
    "\n",
    "In the above table, `-` denotes batch-type dimensions, 🗙 are not allowed, ⟷ are reduced in the operation, ★ are active\n",
    "\n",
    "The preferred way to define a `Shape` is via the `shape()` function.\n",
    "It takes the dimension sizes as keyword arguments.\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "outputs": [],
   "source": [
    "from phi.math import batch, spatial, instance, channel"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "outputs": [
    {
     "data": {
      "text/plain": "(vectorᶜ=x,y)"
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "channel(vector='x,y')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "outputs": [
    {
     "data": {
      "text/plain": "(examplesᵇ=10)"
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch(examples=10)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "outputs": [
    {
     "data": {
      "text/plain": "(xˢ=4, yˢ=3)"
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "spatial(x=4, y=3)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "outputs": [
    {
     "data": {
      "text/plain": "(pointsⁱ=5)"
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "instance(points=5)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "\n",
    "`Shape` objects should be considered *immutable*.\n",
    "Do not change any property of a `Shape` directly.\n",
    "\n",
    "Important `Shape` properties (see the [API documentation](phi/math/#phi.math.Shape) for a full list):\n",
    "\n",
    "* `.sizes: tuple` enumerates the sizes as ints or None, similar to NumPy's shapes.\n",
    "* `.names: tuple` enumerates the dimension names.\n",
    "* `.rank: int` or `len(shape)` number of dimensions.\n",
    "* `.batch, .spatial, .instance, .channel: Shape` or `math.batch(shape)` Filter by dimension type.\n",
    "* `.non_batch: Shape` etc. Filter by dimension type.\n",
    "* `.volume` number of elements a tensor of this shape contains.\n",
    "\n",
    "Important `Shape` methods:\n",
    "\n",
    "* `get_size(dim)` returns the size of a dimension.\n",
    "* `get_item_names(dim)` returns the names given to slices along a dimension.\n",
    "* `without(dims)` drops the specified dimensions.\n",
    "* `only(dims)` drops all other dimensions.\n",
    "\n",
    "Additional tips and tricks\n",
    "\n",
    "* `'x' in shape` tests whether a dimension by the name of 'x' is present.\n",
    "* `shape1 == shape2` tests equality including names, types and order of dimensions.\n",
    "* `shape1 & shape2` or `math.merge_shapes()` combines the shapes."
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## Tensor Creation\n",
    "\n",
    "The [`tensor()` function](phi/math/#phi.math.tensor)\n",
    "converts a scalar, a `list`, a `tuple`, a NumPy array or a TensorFlow/PyTorch tensor to a `Tensor`.\n",
    "The dimension names can be specified using the `names` keyword and dimension types are inferred from the names.\n",
    "Otherwise, they are determined automatically."
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "outputs": [
    {
     "data": {
      "text/plain": "(\u001B[94m1\u001B[0m, \u001B[94m2\u001B[0m, \u001B[94m3\u001B[0m)"
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "math.tensor((1, 2, 3))"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "outputs": [
    {
     "data": {
      "text/plain": "\u001B[92m(batchᵇ=1, xˢ=5, yˢ=4, vectorᶜ=x,y)\u001B[0m \u001B[93mfloat64\u001B[0m const \u001B[94m0.0\u001B[0m"
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy\n",
    "math.tensor(numpy.zeros([1, 5, 4, 2]), batch('batch'), spatial('x,y'), channel(vector='x,y'))"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "outputs": [
    {
     "data": {
      "text/plain": "\u001B[92m(xˢ=5, yˢ=4, vectorᶜ=2)\u001B[0m \u001B[93mfloat64\u001B[0m const \u001B[94m0.0\u001B[0m"
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "math.reshaped_tensor(numpy.zeros([1, 5, 4, 2]), [batch(), *spatial('x,y'), channel(vector='x,y')])"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "\n",
    "There are a couple of functions in the `phi.math` module for creating basic tensors.\n",
    "\n",
    "* [`zeros()`](phi/math/#phi.math.zeros)\n",
    "* [`ones()`](phi/math/#phi.math.ones)\n",
    "* [`linspace()`](phi/math/#phi.math.linspace)\n",
    "* [`random_normal()`](phi/math/#phi.math.random_normal)\n",
    "* [`random_uniform()`](phi/math/#phi.math.random_uniform)\n",
    "* [`meshgrid()`](phi/math/#phi.math.meshgrid)\n",
    "\n",
    "Most functions allow the shape of the tensor to be specified via a `Shape` object or alternatively through the keyword arguments.\n",
    "In the latter case, the dimension types are inferred from the names."
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "outputs": [
    {
     "data": {
      "text/plain": "\u001B[92m(xˢ=5, yˢ=4)\u001B[0m \u001B[93mfloat32\u001B[0m const \u001B[94m0.0\u001B[0m"
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "math.zeros(spatial(x=5, y=4))"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "outputs": [
    {
     "data": {
      "text/plain": "(x=\u001B[94m0.3361668288707733\u001B[0m, y=\u001B[94m0.43297749757766724\u001B[0m)"
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "math.random_uniform(channel(vector='x,y'))"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "outputs": [
    {
     "data": {
      "text/plain": "(\u001B[94m0\u001B[0m, \u001B[94m1\u001B[0m, \u001B[94m0\u001B[0m, \u001B[94m1\u001B[0m, \u001B[94m0\u001B[0m, \u001B[94m-2\u001B[0m) along \u001B[92mexamplesᵇ\u001B[0m"
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "math.random_normal(batch(examples=6), dtype=math.DType(int, 32))"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## Backend Selection\n",
    "\n",
    "The `phi.math` library does not implement basic operators directly but rather delegates the calls to another computing library.\n",
    "Currently, it supports three such libraries: NumPy/SciPy, TensorFlow and PyTorch.\n",
    "These are referred to as *backends*.\n",
    "\n",
    "The easiest way to use a certain backend is via the import statement:\n",
    "\n",
    "* [`phi.flow`](phi/flow.html) &rarr; NumPy/SciPy\n",
    "* [`phi.tf.flow`](phi/tf/flow.html) &rarr; TensorFlow\n",
    "* [`phi.torch.flow`](phi/torch/flow.html) &rarr; PyTorch\n",
    "* [`phi.jax.flow`](phi/torch/flow.html) &rarr; Jax\n",
    "\n",
    "This determines what backend is used to create new tensors.\n",
    "Existing tensors created with a different backend will keep using that backend.\n",
    "For example, even if TensorFlow is set as the default backend, NumPy-backed tensors will continue using NumPy functions.\n",
    "\n",
    "The global backend can be set directly using `math.backend.set_global_default_backend()`.\n",
    "Backends also support context scopes, i.e. tensors created within a `with backend:` block will use that backend to back the new tensors.\n",
    "The three backends can be referenced via the global variables `phi.math.NUMPY`, `phi.tf.TENSORFLOW` and `phi.torch.TORCH`.\n",
    "\n",
    "When passing tensors of different backends to one function, an automatic conversion will be performed,\n",
    "e.g. NumPy arrays will be converted to TensorFlow or PyTorch tensors."
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "outputs": [],
   "source": [
    "from phi.math import backend"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "outputs": [
    {
     "data": {
      "text/plain": "NumPy"
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "backend.default_backend()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "PyTorch\n"
     ]
    }
   ],
   "source": [
    "from phi.torch import TORCH\n",
    "with TORCH:\n",
    "    print(math.zeros().default_backend)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "outputs": [],
   "source": [
    "backend.set_global_default_backend(backend.NUMPY)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "\n",
    "## Indexing, Slicing, Unstacking\n",
    "\n",
    "Indexing is read-only.\n",
    "The recommended way of indexing or slicing tensors is using the syntax\n",
    "```python\n",
    "tensor.<dim>[start:end:step]\n",
    "```\n",
    "where `start >= 0`, `end` and `step > 0` are integers.\n",
    "The access `tensor.<dim>` returns a temporary [`TensorDim`](https://tum-pbs.github.io/PhiFlow/phi/math/#phi.math.TensorDim)\n",
    "object which can be used for slicing and unstacking along a specific dimension.\n",
    "This syntax can be chained to index or slice multiple dimensions."
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "outputs": [
    {
     "data": {
      "text/plain": "\u001B[92m(yˢ=8, zˢ=10)\u001B[0m \u001B[93mfloat32\u001B[0m  \u001B[94m0.509 ± 0.298\u001B[0m \u001B[37m(6e-03...1e+00)\u001B[0m"
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = math.random_uniform(spatial(x=10, y=10, z=10), channel(vector='x,y,z'))\n",
    "data.x[0].y[1:-1].vector['x']"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "Alternatively tensors can be indexed using a dictionary of the form `tensor[{'dim': slice or int}]`."
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'NativeTensor' object is not callable",
     "output_type": "error",
     "traceback": [
      "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[1;31mTypeError\u001B[0m                                 Traceback (most recent call last)",
      "\u001B[1;32m<ipython-input-36-89a59d58fc81>\u001B[0m in \u001B[0;36m<module>\u001B[1;34m\u001B[0m\n\u001B[1;32m----> 1\u001B[1;33m \u001B[0mdata\u001B[0m\u001B[1;33m[\u001B[0m\u001B[1;33m{\u001B[0m\u001B[1;34m'x'\u001B[0m\u001B[1;33m:\u001B[0m \u001B[1;36m0\u001B[0m\u001B[1;33m,\u001B[0m \u001B[1;34m'y'\u001B[0m\u001B[1;33m:\u001B[0m \u001B[0mslice\u001B[0m\u001B[1;33m(\u001B[0m\u001B[1;36m1\u001B[0m\u001B[1;33m,\u001B[0m \u001B[1;33m-\u001B[0m\u001B[1;36m1\u001B[0m\u001B[1;33m)\u001B[0m\u001B[1;33m,\u001B[0m \u001B[1;34m'vector'\u001B[0m\u001B[1;33m:\u001B[0m \u001B[1;34m'x'\u001B[0m\u001B[1;33m}\u001B[0m\u001B[1;33m]\u001B[0m\u001B[1;33m\u001B[0m\u001B[1;33m\u001B[0m\u001B[0m\n\u001B[0m",
      "\u001B[1;31mTypeError\u001B[0m: 'NativeTensor' object is not callable"
     ]
    }
   ],
   "source": [
    "data[{'x': 0, 'y': slice(1, -1), 'vector': 'x'}]"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "Dimensions can be iterated over or unstacked."
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001B[92m(yˢ=10, zˢ=10)\u001B[0m \u001B[93mfloat32\u001B[0m  \u001B[94m0.516 ± 0.284\u001B[0m \u001B[37m(3e-02...1e+00)\u001B[0m\n",
      "\u001B[92m(yˢ=10, zˢ=10)\u001B[0m \u001B[93mfloat32\u001B[0m  \u001B[94m0.504 ± 0.292\u001B[0m \u001B[37m(2e-03...1e+00)\u001B[0m\n",
      "\u001B[92m(yˢ=10, zˢ=10)\u001B[0m \u001B[93mfloat32\u001B[0m  \u001B[94m0.512 ± 0.301\u001B[0m \u001B[37m(5e-03...1e+00)\u001B[0m\n",
      "\u001B[92m(yˢ=10, zˢ=10)\u001B[0m \u001B[93mfloat32\u001B[0m  \u001B[94m0.509 ± 0.290\u001B[0m \u001B[37m(2e-04...1e+00)\u001B[0m\n",
      "\u001B[92m(yˢ=10, zˢ=10)\u001B[0m \u001B[93mfloat32\u001B[0m  \u001B[94m0.497 ± 0.282\u001B[0m \u001B[37m(8e-03...1e+00)\u001B[0m\n",
      "\u001B[92m(yˢ=10, zˢ=10)\u001B[0m \u001B[93mfloat32\u001B[0m  \u001B[94m0.531 ± 0.287\u001B[0m \u001B[37m(2e-05...1e+00)\u001B[0m\n",
      "\u001B[92m(yˢ=10, zˢ=10)\u001B[0m \u001B[93mfloat32\u001B[0m  \u001B[94m0.477 ± 0.279\u001B[0m \u001B[37m(4e-03...1e+00)\u001B[0m\n",
      "\u001B[92m(yˢ=10, zˢ=10)\u001B[0m \u001B[93mfloat32\u001B[0m  \u001B[94m0.514 ± 0.262\u001B[0m \u001B[37m(2e-02...1e+00)\u001B[0m\n",
      "\u001B[92m(yˢ=10, zˢ=10)\u001B[0m \u001B[93mfloat32\u001B[0m  \u001B[94m0.492 ± 0.281\u001B[0m \u001B[37m(7e-03...1e+00)\u001B[0m\n",
      "\u001B[92m(yˢ=10, zˢ=10)\u001B[0m \u001B[93mfloat32\u001B[0m  \u001B[94m0.494 ± 0.301\u001B[0m \u001B[37m(2e-03...1e+00)\u001B[0m\n"
     ]
    }
   ],
   "source": [
    "for slice in data.x:\n",
    "    print(slice)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "outputs": [
    {
     "data": {
      "text/plain": "(\u001B[92m(yˢ=10, zˢ=10, vectorᶜ=x,y,z)\u001B[0m \u001B[93mfloat32\u001B[0m  \u001B[94m0.504 ± 0.297\u001B[0m \u001B[37m(4e-04...1e+00)\u001B[0m,\n \u001B[92m(yˢ=10, zˢ=10, vectorᶜ=x,y,z)\u001B[0m \u001B[93mfloat32\u001B[0m  \u001B[94m0.491 ± 0.290\u001B[0m \u001B[37m(1e-02...1e+00)\u001B[0m,\n \u001B[92m(yˢ=10, zˢ=10, vectorᶜ=x,y,z)\u001B[0m \u001B[93mfloat32\u001B[0m  \u001B[94m0.507 ± 0.286\u001B[0m \u001B[37m(3e-03...1e+00)\u001B[0m,\n \u001B[92m(yˢ=10, zˢ=10, vectorᶜ=x,y,z)\u001B[0m \u001B[93mfloat32\u001B[0m  \u001B[94m0.514 ± 0.291\u001B[0m \u001B[37m(4e-06...1e+00)\u001B[0m,\n \u001B[92m(yˢ=10, zˢ=10, vectorᶜ=x,y,z)\u001B[0m \u001B[93mfloat32\u001B[0m  \u001B[94m0.520 ± 0.292\u001B[0m \u001B[37m(2e-03...1e+00)\u001B[0m,\n \u001B[92m(yˢ=10, zˢ=10, vectorᶜ=x,y,z)\u001B[0m \u001B[93mfloat32\u001B[0m  \u001B[94m0.485 ± 0.287\u001B[0m \u001B[37m(4e-03...1e+00)\u001B[0m,\n \u001B[92m(yˢ=10, zˢ=10, vectorᶜ=x,y,z)\u001B[0m \u001B[93mfloat32\u001B[0m  \u001B[94m0.520 ± 0.286\u001B[0m \u001B[37m(8e-04...1e+00)\u001B[0m,\n \u001B[92m(yˢ=10, zˢ=10, vectorᶜ=x,y,z)\u001B[0m \u001B[93mfloat32\u001B[0m  \u001B[94m0.528 ± 0.281\u001B[0m \u001B[37m(7e-03...1e+00)\u001B[0m,\n \u001B[92m(yˢ=10, zˢ=10, vectorᶜ=x,y,z)\u001B[0m \u001B[93mfloat32\u001B[0m  \u001B[94m0.503 ± 0.294\u001B[0m \u001B[37m(8e-03...1e+00)\u001B[0m,\n \u001B[92m(yˢ=10, zˢ=10, vectorᶜ=x,y,z)\u001B[0m \u001B[93mfloat32\u001B[0m  \u001B[94m0.509 ± 0.287\u001B[0m \u001B[37m(1e-03...1e+00)\u001B[0m)"
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tuple(data.x)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## Non-uniform Tensors\n",
    "\n",
    "The `math` package allows tensors of varying sizes to be stacked into a single tensor.\n",
    "This tensor then has dimension sizes of type `Tensor` where the source tensors vary in size.\n",
    "\n",
    "One use case of this are `StaggeredGrid`s where the tensors holding the vector components have different shapes."
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "outputs": [
    {
     "data": {
      "text/plain": "\u001B[92m(aˢ=(\u001B[94m4\u001B[0m, \u001B[94m5\u001B[0m) along \u001B[92mcᶜ\u001B[0m, bˢ=2, cᶜ=2)\u001B[0m \u001B[93mfloat32\u001B[0m const \u001B[94m0.5\u001B[0m"
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "t0 = math.zeros(spatial(a=4, b=2))\n",
    "t1 = math.ones(spatial(b=2, a=5))\n",
    "stacked = math.stack([t0, t1], channel('c'))\n",
    "stacked"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "outputs": [
    {
     "data": {
      "text/plain": "False"
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "stacked.shape.is_uniform"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## Data Types and Precision\n",
    "\n",
    "The package `phi.math` provides a custom [`DataType` class](phi/math/#phi.math.DType) that can be used with all backends.\n",
    "There are no global variables for common data types; instead you can create one by specifying the kind and length in bits."
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "outputs": [],
   "source": [
    "from phi.math import DType"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "outputs": [
    {
     "data": {
      "text/plain": "float32"
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "DType(float, 32)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "outputs": [
    {
     "data": {
      "text/plain": "complex128"
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "DType(complex, 128)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "outputs": [
    {
     "data": {
      "text/plain": "bool8"
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "DType(bool)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "By default, floating point operations use 32 bit (single precision). This can be changed globally using [`math.set_global_precision(64)`](phi/math/#phi.math.set_global_precision) or locally using [`with math.precision(64):`](phi/math/#phi.math.precision).\n",
    "\n",
    "This setting does not affect integers. To specify the number of integer bits, use [`math.to_int()`](phi/math/#phi.math.to_int) or cast the data type directly using [`math.cast()`](phi/math/#phi.math.cast)."
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## Printing Options\n",
    "\n",
    "Tensors can be printed in a variety of ways. These options can be specified in the format string, separated by colons. Here is an example:"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "print(f\"{math.zeros(spatial(x=8, y=6)):summary:color:shape:dtype:.5e}\")"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "The order of the arguments is not important.\n",
    "\n",
    "### Layout\n",
    "The layout determines what is printed and where. The following options are available:\n",
    "\n",
    "* `summary` Summarizes the values by mean, standard deviation, minimum and maximum value.\n",
    "* `row` Prints the tensor as a single-line vector.\n",
    "* `full` Prints all values in the tensors as a multi-line string.\n",
    "* `numpy` Uses the formatting of NumPy\n",
    "\n",
    "### Additional Information\n",
    "\n",
    "The keywords `shape`, `no-shape`, `dtype` and `no-dtype` can be used to show or hide additional properties of the tensor.\n",
    "\n",
    "### Color\n",
    "\n",
    "Use the keywords `color` or `no-color`.\n",
    "Currently `color` will use ANSI color codes which are supported by most terminals, IDEs as well as Jupyter notebooks.\n",
    "\n",
    "### Number Format\n",
    "\n",
    "You can additionally specify a format string for floating-point numbers like `.3f` or `.2e`."
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}